package org.ziegler.jvm.cp7.ot;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

public class ClassLoaderTest {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        ClassLoader myLoader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                try {
                    final String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    final InputStream is = getClass().getResourceAsStream(fileName);
                    final byte[] b = new byte[is.available()];
                    is.read(b);

                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        final Object o = myLoader.loadClass("org.ziegler.jvm.cp7.ot.ClassLoaderTest").getDeclaredConstructor()
                .newInstance();
        System.out.println("o = " + o.getClass());
        System.out.println(o instanceof ClassLoaderTest);
        System.out.println(o instanceof ClassLoaderTest);

        final ClassLoaderTest classLoaderTest = new ClassLoaderTest();
        System.out.println("classLoaderTest.getClass() = " + classLoaderTest.getClass());
        System.out.println(classLoaderTest instanceof ClassLoaderTest);

//        ClassLoader myLoader2 = new ClassLoader() {
//            @Override
//            public Class<?> loadClass(String name) throws ClassNotFoundException {
//
//                try {
//                    final String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
//                    final InputStream is = getClass().getResourceAsStream(fileName);
//                    if (is == null) {
//                        return super.loadClass(name);
//                    }
//
//                    final byte[] b = new byte[is.available()];
//                    is.read(b);
//
//                    return super.loadClass(name);
//                } catch (IOException e) {
//                    throw new ClassNotFoundException(name);
//                }
//            }
//        };



//        final Object o2 = myLoader2.loadClass("org.ziegler.jvm.cp7.ClassLoaderTest").getDeclaredConstructor()
//                .newInstance();
//        System.out.println("o2 = " + o2.getClass());
//        System.out.println(o2 instanceof org.ziegler.jvm.cp7.ClassLoaderTest);
//
//

    }
}
